import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'network/data.dart';
import 'dart:async';
import 'dart:convert' show utf8, json;
import 'config.dart';

class ReadBody extends StatefulWidget {
  int bookid;
  int chapterid;

  double screenWidth;

  double screenHeight;

  ReadBody(int bookid,int chapterid ,double screenWidth,double screenHeight){
    this.bookid = bookid;
    this.chapterid = chapterid;
    this.screenHeight = screenHeight;
    this.screenWidth = screenWidth;
  }

  @override
  createState()=>new ReadBodyState(bookid,chapterid,screenWidth,screenHeight);

}

class ReadBodyState extends State<ReadBody>{

  // 手工计算得出，单倍行高应该为10.0左右，因此可以计算出单个页面所有的文字数量了。


  // 书籍id
  int bookid;

  // 当前章节id
  int chapterid;

  // 上一个章节id
  int previousChapterid;

  // 下一个章节id
  int nextChapterid;

  // 当前章节总页数
  int totalPageNum;

  // 书籍所有的map信息
  Map theChapterInfo;

  // 章节所包含的所有的文字信息
  List chapterContent;

  // 章节每页的最后列的表
  List<int> chapterEndIndex;

  // 章节要展示的内容
  String showingContent = "";

  // 当前章节展示的页面
  int page = 0;

  // 当前页所能展示的文字的数量，包含空格
  int wordNumInPage = 0;

  // 当前页所能展示的每行的文字数量
  int wordPerline = 0;

  // 当前页所能展示的文字的行数
  int wordLineNum = 0;

  double screenWidth;

  double screenHeight;



  // 字体大小
  double chapterContentFontSize = 20.0;

  ReadBodyState(int bookid,int chapterid,[double screenWidth=0.00,double,screenHeight=0.00]){
    this.bookid= bookid;
    this.chapterid = chapterid;
    this.screenHeight = screenHeight;
    this.screenWidth = screenWidth;

  }



  void _knowWordNumPerPage(){
    double width = this.screenWidth;
    double height = this.screenHeight;
    print("到这一步没出错0");
    int wordPerLine = width ~/ chapterContentFontSize;
    print("到这一步没出错");
    int lines = height ~/ (chapterContentFontSize * 3 / 2);// 具体是规定的10还是20/2 得看一下
    int wordNumPerPage = wordPerLine * lines;
    this.wordNumInPage = wordNumPerPage;
    this.wordPerline = wordPerLine;
    this.wordLineNum = lines;
  }

  int _knowLinesPerP(int i){
    int leftWordNum = chapterContent[i].toString().length % wordPerline;
    int currentLines = chapterContent[i].toString().length ~/ wordPerline;
    if(leftWordNum >0){
      currentLines +=1;
    }
    return currentLines;
  }

  /**
   * 获取本章页数
   */
  int _konwTotalPageNum(size){
    int pages = 0;
    int tmpLineNums = 0;
    for(int i =0 ;i<size;i++){
      int currentPLines = _knowLinesPerP(i);
      tmpLineNums += currentPLines;
      if(i+1<size){
        int nextLineNums = _knowLinesPerP(i+1);
        if(tmpLineNums+nextLineNums > wordLineNum){
          pages+=1;
          tmpLineNums = 0;
          print(i);
          chapterEndIndex.add(i);
        }
      }else{
        pages +=1;
        chapterEndIndex.add(i);
      }
    }
    return pages;
  }

  /**
   * 加载章节信息
   * type 当为0 时，正常加载，当为-1时，加载上一章节的最后一页，当为1时加载下一章节的第一页
   */
  void _loadChapterContent(int chapterid,int bookid,[int type=0]){
    RequestData requestData = new RequestData();
    Future<String> response = requestData.baseRequest(config.baseDomain, "/api/chapter/"+bookid.toString()+"/"+chapterid.toString(), "get");
    response.then((value){
      Map data = json.decode(value);
      print(data);
      theChapterInfo = data["data"];
      print(theChapterInfo);
      if(theChapterInfo["previousChapterId"] != null){
        this.previousChapterid = theChapterInfo["previousChapterId"];
      }
      if(theChapterInfo["nextChapterId"] != null){
        this.nextChapterid = theChapterInfo["nextChapterId"];
      }
      this.chapterid = chapterid;
      chapterContent = data["data"]["currentChapterContent"];
      this.totalPageNum = _konwTotalPageNum(chapterContent.length);
      if(type == -1){
       page = this.totalPageNum - 1;
      }else{
        page = 0;
      }
      _makeShowingContent();
    }).catchError((err){
      print(err);
    });

  }



  @override
  void initState() {
    // 实现初始化
    super.initState();
    _knowWordNumPerPage();
    _loadChapterContent(this.chapterid, this.bookid);

  }
  
  // 0 代表上一页，1 代表拉出工具栏，2代表下一页
  int _caculatePositionAction(double touchx,double touchy,double swidth,double sheight){
    if(touchx<swidth/3){
      return 0;
    }
    if(touchx>swidth/3 && touchx<swidth/3*2){
      if(touchy<sheight/3){
        return 0;
      }else if(touchy>sheight/3 && touchy<sheight/3*2){
        return 1;
      }else {
        return 2;
      }
    }
    return 2;
  }

  // 制作显示的内容
  void _makeShowingContent(){
    var theShowingContent = "";
    int startRange = 0 ;
    int endRange = chapterEndIndex[page] + 1;
    Iterable toShowList;

    if(page > 0 ){
      startRange =chapterEndIndex[page-1]+1;
    }

    toShowList = chapterContent.getRange(startRange, endRange);
    toShowList.forEach((value){
      theShowingContent = theShowingContent+"\n\u3000\u3000"+value.toString();
    });


//    if(chapterContent.length-(1+page)*config.pPerPage >0){
//      for(int i =page*config.pPerPage;i<(1+page)*config.pPerPage;i++){
//        theShowingContent = theShowingContent+"\n\u3000\u3000"+chapterContent[i];
//      }
//    }else{
//      for(int i =page*config.pPerPage;i<chapterContent.length;i++){
//        theShowingContent = theShowingContent+"\n\u3000\u3000"+chapterContent[i];
//      }
//    }
//    print(MediaQuery.of(context).size);
    this.setState((){
      this.showingContent = theShowingContent;
    });
//    print(this.showingContent);
  }

  // 制作显示章节内容的组件
  Widget _buildReadChapterContent(BuildContext context){



    var currentScreenWidth = MediaQuery.of(context).size.width;
    var currentScreenHeight = MediaQuery.of(context).size.height;
    return new GestureDetector(
      onTapDown: (detail){
        print("down了");
        print(detail.globalPosition);
        int action = _caculatePositionAction(detail.globalPosition.dx, detail.globalPosition.dy, currentScreenWidth, currentScreenHeight);
        if(action == 0){
          print("向上翻页");
          if(page>=0){
            page = page - 1;
          }

          if(page>=0){
            _makeShowingContent();
          }else{
           if(this.previousChapterid == -1){
             showDialog(context: context,builder: (BuildContext context){
               return new AlertDialog(
                 title: new Text("提示"),
                 content: new SingleChildScrollView(
                   child: new ListBody(
                     children: <Widget>[
                       new Text("小说已经到了最前面的章节了")
                     ],
                   ),
                 ),
                 actions: <Widget>[
                   new FlatButton(onPressed: (){ Navigator.of(context).pop();}, child: new Text("知道了"))
                 ],
               );
             });
           }else{
             _loadChapterContent(this.previousChapterid, bookid,-1);
           }
          }
        }else if (action == 1){
          print("调出工具栏");
        }else {
          print("向下翻页");
          page = page + 1;
          if(page < totalPageNum){
            _makeShowingContent();
          }else{
            _loadChapterContent(this.nextChapterid, bookid);
          }
        }
      },
      child:new Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        child:
        new RichText(
            text: new TextSpan(
                text: showingContent,
                style: new TextStyle(color: Colors.black,fontSize: chapterContentFontSize)
            )
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      primary: true,
      body:_buildReadChapterContent(context)
    );
  }

}